package com.ictech.print.ui;

import java.util.Timer;
import java.util.TimerTask;

import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.webkit.ValueCallback;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.Toast;

import com.ictech.client.R;
import com.ictech.print.event.HideNavEvent;
import com.ictech.print.event.JsEvent;
import com.ictech.print.event.SwitchScreenEvent;
import com.ictech.print.ui.base.BaseActivity;
import com.ictech.print.utils.JsonUtil;
import com.ictech.print.utils.PreferencesUtil;
import com.ictech.print.web.AndroidtoJs;
import com.tencent.bugly.beta.Beta;

import de.greenrobot.event.EventBus;

import com.ictech.print.service.PrinterService;
import com.tencent.tinker.loader.hotplug.interceptor.HandlerMessageInterceptor;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import static com.ictech.print.job.PrintJob.mPrinterMethodAgent;

public class MainActivity extends BaseActivity {

	private final String TAG = "MainActivity";

	private WebView mWebView;
	private Button print;

	private Timer timer = new Timer();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		/***********************打印测试*****************/
		final String content = "[{\"orderId\":\"260418010057420181221574_23\",\"time\":\"2018-12-21 08:45:45\",\"totalPrice\":\"0.4\"," +
				"\"trace_url\":\"http://14.215.237.131:8085/cszs/search.do?no=44090200500030000046\"," +
				"\"detail\":[" +
				"{\"name\":\"商品名称\",\"weight\":\"20.00\",\"weight_unit\":\"1\",\"price\":\"10.00\"}," +
				"{\"name\":\"商品名称测试\",\"weight\":\"20.00\",\"weight_unit\":\"1\",\"price\":\"10.00\"}," +
				"{\"name\":\"这是一个测试用的商品名称\",\"weight\":\"20.00\",\"weight_unit\":\"1\",\"price\":\"10.00\"}," +
				"{\"name\":\"这是另一个测试用的商品名称\",\"weight\":\"20.00\",\"weight_unit\":\"1\",\"price\":\"10.00\"}" +
				"]}]";
		print = (Button)findViewById(R.id.bt_acPrint);
		print.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				/*打印测试*/
				Thread testPrint =  new Thread(new Runnable() {
					@Override
					public void run() {
						if (mPrinterMethodAgent != null){
							if (mPrinterMethodAgent.printBill(content)) {
								Log.i(TAG, "打印成功");
							} else {
								Log.i(TAG, "打印失败");
							}
						}else {
							Log.i(TAG, "打印机离线");
						}
					}
				});
				testPrint.start();
			}
		});
		/**************************************/

		/*获取蓝牙打印机的Mac地址，并进行服务绑定*/
        getPrinterMac();
		
		String so = PreferencesUtil.get("so");
		int screenOrienation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
		if (so != null && so.length() != 0) {
			try {
				screenOrienation = Integer.valueOf(so);
			} catch(Exception e) {
			}
			if (screenOrienation != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE 
					&& screenOrienation != ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE) {
				screenOrienation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
			}
		}
		if(getRequestedOrientation() != screenOrienation) {
			setRequestedOrientation(screenOrienation);
			PreferencesUtil.set("so", "" + screenOrienation);
	    }

		// 设置不屏保
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

		findViewById();
		initView();
		
		EventBus.getDefault().register(this, "switchScreen", SwitchScreenEvent.class);
		EventBus.getDefault().register(this, "js", JsEvent.class);
		
		hideNavigationBar();
		
		new Handler().postDelayed(new Runnable(){    
		    public void run() {    
		    	// 检查更新
				// 参数1：isManual 用户手动点击检查，非用户点击操作请传false
				// 参数2：isSilence 是否显示弹窗等交互，[true:没有弹窗和toast] [false:有弹窗或toast]
				Beta.checkUpgrade(false, false);
		    }    
		 }, 30000);
		
		executeTask();
	}
	
	private void executeTask() {
		TimerTask task = new TimerTask() {
			@Override
			public void run() {
				try {
					EventBus.getDefault().post(new HideNavEvent());
				} catch (Exception e) {
				}
			}
		};
		timer.schedule(task, 2000, 5000);
	}
	
	public void hideNavMainThread(HideNavEvent event) {
		hideNavigationBar();
	}
	
	// 隐藏虚拟按键
    public void hideNavigationBar() {
        int uiFlags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                | View.SYSTEM_UI_FLAG_FULLSCREEN; // hide status bar

        if( android.os.Build.VERSION.SDK_INT >= 19 ){
            uiFlags |= 0x00001000;    //SYSTEM_UI_FLAG_IMMERSIVE_STICKY: hide navigation bars - compatibility: building API level is lower thatn 19, use magic number directly for higher API target level
        } else {
            uiFlags |= View.SYSTEM_UI_FLAG_LOW_PROFILE;
        }
        getWindow().getDecorView().setSystemUiVisibility(uiFlags);
    }
	
	public void jsMainThread(JsEvent event) {
		if (event != null && event.getJs() != null
				&& event.getJs().length() > 0) {
			mWebView.loadUrl("javascript:" + event.getJs());
		}
	}
	
	public void switchScreenMainThread(SwitchScreenEvent switchScreenEvent) {
		if(getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
	        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
	        PreferencesUtil.set("so", "" + ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
	    } else {
	    	setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
	    	PreferencesUtil.set("so", "" + ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
	    }
	}
	
	@Override
	protected void findViewById() {
		mWebView = (WebView) findViewById(R.id.webview);
	}

	@Override
	protected void initView() {
		mWebView.getSettings().setJavaScriptEnabled(true);
		mWebView.addJavascriptInterface(new AndroidtoJs(), "client");
		mWebView.loadUrl("file:///android_asset/client/index.html");
	}


	/*打印机相关代码*/
	private final int REQUEST_BL_PRINTER = 0;
	private Intent mPrinterIntent;
	private PrinterReceiver mPrinterReceiver = null;


    /**
     * 开启打印机服务
     */
    public void startPrinterService(){
        mPrinterIntent = new Intent(MainActivity.this, PrinterService.class);
		if (startService(mPrinterIntent) != null){
			registerPeripheralBroadcastReceiver(true);
            Log.i(TAG,"连接中...");
		}
	}

    /**
     * 关闭打印机服务
     */
    public void stopPrinterService(){
    	if (mPrinterIntent != null){
			if (stopService(mPrinterIntent)){
				registerPeripheralBroadcastReceiver(false);
				Log.i(TAG,"打印机服务已关闭");
			}else {
				Log.i(TAG,"打印机服务不存在");
			}
		}
	}

	/**
	 * 注册外设服务广播接受者
	 * @param state     注册还是取消注册
	 */
	private void registerPeripheralBroadcastReceiver(boolean state){
		if (state){
			IntentFilter mfilter = new IntentFilter();
			mfilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
			mfilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
			mfilter.addAction(PrinterService.ACTION_PRINTER_SOCKER_ERROR);
			mfilter.addAction(PrinterService.ACTION_PRINTER_SERVICE_CONNECT);
			mPrinterReceiver = new PrinterReceiver();
			registerReceiver(mPrinterReceiver, mfilter);
		}else if (mPrinterReceiver != null){
			unregisterReceiver(mPrinterReceiver);
			mPrinterReceiver = null;
		}
	}

    /**
     * 接收打印机服务广播的消息
     */
    private class PrinterReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if((BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) ||
					(PrinterService.ACTION_PRINTER_SERVICE_CONNECT.equals(action))){
				Log.i(TAG,"连接打印机成功");
				/*绑定蓝牙打印机服务*/
				printerServiceConn mPrinterServiceConn = new printerServiceConn();
				bindService(mPrinterIntent,mPrinterServiceConn,0);
			}else if((BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) ||
					(PrinterService.ACTION_PRINTER_SOCKER_ERROR.equals(action))){
				stopPrinterService();
				mPrinterMethodAgent = null;
				Log.i(TAG,"连接打印机失败");
			}
		}
	}

	/*获取打印机的mac地址*/
	private void getPrinterMac(){
		Intent mIntent = new Intent(this, Activity_DeviceList.class);
		startActivityForResult(mIntent, REQUEST_BL_PRINTER);
	}

    @Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == REQUEST_BL_PRINTER && resultCode == RESULT_OK) {
			String printerMac = data.getStringExtra(Activity_DeviceList.EXTRA_DEVICE_ADDRESS);
			PreferencesUtil.set("printerMac",printerMac);
			Log.i(TAG,"获取了mac地址");
		}

		/*开启打印服务*/
		startPrinterService();
	}

	class printerServiceConn implements ServiceConnection {
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mPrinterMethodAgent = (PrinterService.MethodAgent)service;
			//如果直接在这测试打印，每次都需要重新配对才行，所以改了点击按钮再执行测试。
			Log.i(TAG,"成功绑定服务");
        }

		@Override
		public void onServiceDisconnected(ComponentName name) {
			Log.i(TAG,"disconnect");
		}
	}


	@Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG,"onDestroy");
        stopPrinterService();
    }
}
